import { defineStore } from "pinia"
import { login, getUser } from "@/api/user"

import Cookies from "js-cookie"
import { getAddRoute } from "@/router/routeCon"
import { RouteRecordRaw } from "vue-router"
import { userType } from "@/type/pinia"
export const userStore = defineStore({
    id: "user",
    state: (): userType => {
        return {
            name: "zzx",
            token: "",
            userInfo: {},
            routes: [],
            cheList: {},
        }
    },
    actions: {
        // async getToken() {
        //     const res = await login()
        //     if (res.code == 200) {
        //         const token = res.data.token
        //         this.token = token
        //         // 将token值添加到cookie中
        //         setCookie(token)
        //     } else {
        //         Promise.reject(new Error("faile"))
        //     }
        // },
        // 拉取用户信息
        async getUserInfo() {
            const res: any = await getUser()
            if (res.code == 200) {
                Cookies.set("username", res.data.role)
                this.userInfo = res.data
                //获取动态路由
                const addRoutes: RouteRecordRaw = await getAddRoute(res.data.role)
                console.log(addRoutes);

                if (this.routes.length === 0) {
                    this.routes.push(addRoutes)
                }
                return Promise.resolve()
            } else {
                Promise.reject(new Error("faile"))
                Promise.reject(new Error("faile"))
            }
        },
        // 缓存路由'
        setacheList(ach: RouteRecordRaw) {
            this.cheList = ach
        }
    }
})